package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 拿到用户输入的密码后 先把用户输入的密码通过 MD5加密 再去数据库中校验
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("md5Password:{}", password);

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        // 获取用户输入的信息 封装为Employee
        Employee employee = new Employee();
        employee.setName(employeeDTO.getName());
        employee.setUsername(employeeDTO.getUsername());
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));// 采用默认密码
        employee.setPhone(employeeDTO.getPhone());
        employee.setSex(employeeDTO.getSex());
        employee.setIdNumber(employeeDTO.getIdNumber());
        employee.setStatus(StatusConstant.ENABLE);// 默认启用

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        // 写入当前数据的创建者 和 修改者 即 当前对象
//        employee.setCreateUser(BaseContext.threadLocalEmpId.get());
//        employee.setUpdateUser(BaseContext.threadLocalEmpId.get());

        log.info("[业务层：{}]", employee);

        employeeMapper.insertEmployee(employee);
    }

    /**
     * 员工分页查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pageListEmployee(EmployeePageQueryDTO pageQueryDTO) {
        log.info("[业务层EmployeePageQueryDTO：{}]", pageQueryDTO);
        // 设置分页格式
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        List<Employee> employees = employeeMapper.selectEmployee(pageQueryDTO.getName());
        Page<Employee> employeePage = (Page<Employee>) employees;

        return new PageResult(employeePage.getTotal(), employeePage.getResult());
    }

    /**
     * 修改员工账号状态
     * @param status
     * @param id
     */
    @Override
    public void updateEmployeeStatus(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee findEmpById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 将DTO对象内容拷贝至 员工对象
        BeanUtils.copyProperties(employeeDTO, employee);

        // 更新修改信息的人和时间
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        log.info("[修改员工业务层] employee:{}", employee);

        // 调用mapper
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 修改员工密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        log.info("[修改密码]{}", passwordEditDTO);
        // 获取当前登录中的员工
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        Employee employee = employeeMapper.selectById(passwordEditDTO.getEmpId());
        if (employee == null) {
            // 当前员工信息不存在
            throw new BaseException("当前信息异常！！");
        }

        // 获取到用户输入的原密码
        String oldPassword = passwordEditDTO.getOldPassword();
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());

        // 用员工当的密码与用户输入的原密码进行比较
        if (!employee.getPassword().equals(oldPassword)) {
            // 验证不通过 无法修改密码
            throw new BaseException("原密码输入错误！");
        }

        // 验证通过了 可以改密码
        String newPassword = passwordEditDTO.getNewPassword();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());

        employee.setPassword(newPassword);

        employeeMapper.updateEmployee(employee);
    }

}
